package com.kmair.caiwu.financialexpress.util;


import net.sourceforge.jeval.EvaluationException;
import net.sourceforge.jeval.Evaluator;

import java.util.ArrayList;
import java.util.List;

/**
 * 字符串公式计算
 * by isi on 2016/11/30.
 */
public class StringEval {
    public static char PLUS = '+';
    public static char MINUS = '-';
    public static char MULTI = '*';
    public static char DEVIDE = '/';

    public static char BRACKET_LEFT = '(';
    public static char BRACKET_RIGHT = ')';
    private final DataChangeUtil dataChange;


    public StringEval(DataChangeUtil dataChange) {
        this.dataChange = dataChange;
    }

    /**
     * 将字符串公式转换成List 如”12+3-4" 变成 12，+，3，-，4
     *
     * @param line
     * @return
     */
    private List<String> stringToStringList(String line) {
        StringBuilder sb = new StringBuilder();
        List<String> stringList = new ArrayList<String>();
        char[] ch = line.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (ch[i] == PLUS || ch[i] == MINUS || ch[i] == MULTI || ch[i] == DEVIDE) {
                stringList.add(sb.toString());
                stringList.add(String.valueOf(ch[i]));
                sb = new StringBuilder();
            } else {
                sb.append(ch[i]);
            }
            if (i == ch.length - 1) {
                stringList.add(sb.toString());
            }
        }
        return stringList;
    }

    /**
     * 将文字描述字符串转成对应的计算公式
     * 如：收入：100，成本：80。输入“收入-成本” 变成“100-80”
     *
     * @param line
     * @return
     */
    public String stringToEvalString(String line, Object entity) {
        List<String> ls = stringToStringList(line);
        StringBuilder sb = new StringBuilder();
        for (String sline :
                ls) {
            char ch = sline.charAt(0);
            if (ch == PLUS || ch == MINUS || ch == MULTI || ch == DEVIDE) {
                sb.append(ch);
            } else {
                String st = dataChange.dataChange(sline, entity);//将公式的科目转换对应的值
                sb.append(st);
            }
        }
        return sb.toString();
    }

    /**
     * 将字符串公式计算出来，
     * 如：输入“1+2”,返“3”
     *
     * @param stringEval
     * @return
     * @throws EvaluationException
     */
    public String evalData(String stringEval) {
        Evaluator evaluator = new Evaluator();
        String s = null;
        try {
            s = evaluator.evaluate(stringEval);
        } catch (EvaluationException e) {
            e.printStackTrace();
        }
        return s;
    }
}



